package org.hose.core;

import cn.hutool.core.exceptions.ExceptionUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.log.Log;
import com.microsoft.playwright.BrowserContext;
import com.microsoft.playwright.Page;
import com.microsoft.playwright.TimeoutError;
import com.microsoft.playwright.options.LoadState;

import static com.microsoft.playwright.assertions.PlaywrightAssertions.assertThat;

public class UICommandPlaywright {
    private static final Log log = Log.get();
    private Page page;
    private BrowserContext context;

    public UICommandPlaywright(Page page, BrowserContext context) {
        this.page = page;
        this.context = context;
    }

    //封装浏览器常用操作
    public void 打开(String url) {
        page.navigate(url);
    }
    public void 点击(String selector) {
        page.click(selector);
    }
    // 双击
    public void 双击(String selector) {
        page.dblclick(selector);
    }
    //复选框
    public void 复选框选中(String selector) {
        page.check(selector);
    }

    public void 输入(String selector, String value) {
        page.fill(selector, value);
    }
    public void 刷新() {
        page.reload();
    }
    //下拉框选择
    public void 下拉框选择(String selector, String value) {
        page.selectOption(selector, value);
    }

    //断言元素存在
    public void 元素存在(String selector) {
        assertThat(page.locator(selector)).isVisible();
    }

    /**
     * 调试: 页面暂停
     */
    public void 调试() {
        page.pause();
    }

    //等所有链接加载完毕
    public void 智能等待() {
        try {
            page.waitForLoadState(LoadState.NETWORKIDLE, new Page.WaitForLoadStateOptions().setTimeout(50000));
        } catch (Exception e) {
            log.error(StrUtil.concat(true, "等待超时, Message: ", e.getMessage()));
            throw ExceptionUtil.wrapRuntime(StrUtil.concat(true, "等待异常, Message: ", e.getMessage()));
        }
    }
}
